import express from 'express';
import Cors from 'cors';
import Session from 'express-session';
import bodyParser from 'body-parser';
import ServerConfig from './config';
import fileRouter from './router/file';
import loginRouter from './router/login';
import path from 'path';

const axios = require('axios');
const app = express();
const server = require('http').Server(app);
const signature = require('cookie-signature');

/***
 * 加载public资源
 **/
app.use(express.static(path.join(__dirname, 'public')));

function modify (config) {
  let obj = Object.assign({}, config);
  let originStep = [];
  obj.cors.origin.forEach(item => {
    originStep.push(new RegExp(item));
  });
  obj.cors.origin = originStep;
  return obj;
}

let Config = modify(ServerConfig);

let {
  Java,
  Local,
  cors,
  LocalURL,
  session,
  SSO,
} = Config;

const host = process.env.HOST || LocalURL.origin;
const port = process.env.PORT || LocalURL.port;

app.set('port', port);

/***
 * Enable All CORS Requests
 **/
app.use(Cors(cors));

/***
 * 启用 session
 **/
app.use(Session(session));

// -------------------------------------------------------------------
//                          模拟 业务层
app.use(bodyParser.json()); // 请求解析 为json格式
app.use(bodyParser.urlencoded({extended: true}));

// -------------------------------------------------------------------

app.use('/file', fileRouter);
app.use(loginRouter);

/***
 * 全局拦截器
 **/
const userInfoFilter = new RegExp(`^/${Local.name}/${Local.userInfo}`);
const loginFilter = new RegExp('(.*/login$)|(.*/login?)');

app.use(async function (req, res, next) {
  if (req.query.ticket && req.query.ckcode) {
    let responseUrl = `${Java.url}/${Local.userInfo}?ticket=${req.query.ticket || 'ticket'}&ckcode=${req.query.ckcode || 'ckcode'}&appcode=${Local.appCode}`;
    let response = await axios({
      method: 'get',
      // url: ssoLogin,
      url: responseUrl,
      headers: {
        'client_ip': req.ip,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
        'Content-Type': 'application/json;charset=UTF-8',
      },
    });
    req.session.JSESSIONID = response.headers['set-cookie'][0].split(';')[0].split('=')[1];
    if (req.session.JSESSIONID) {
      req.session.save();
      if (userInfoFilter.test(req.url)) {
        return res.send(response.data);
      } else {
        req.headers.cookie = `${Local.appCode}=${'s:' + signature.sign(req.session.id, session.secret)};`;
      }
    } else {
      console.error('存在异常 JSESSIONID !   ' + (new Date()).toLocaleTimeString());
    }
  }
  if (typeof req.query.userLogin !== 'undefined') {
    delete req.session.JSESSIONID;
    return next();
  }

  let path = req.url.split('/');
  let appCode = path[1];
  if (appCode && appCode !== Local.name) {
    return next();
  }

  if (userInfoFilter.test(req.url) && req.session.JSESSIONID) {
    let response = await axios({
      method: 'get',
      // url: ssoLogin,
      url: `${Java.originUrl}/${Local.userInfo}`,
      headers: {
        'client_ip': req.ip,
        'Cookie': `JSESSIONID=${req.session.JSESSIONID};`,
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
        'Content-Type': 'application/json;charset=UTF-8',
      },
    });
    return res.send(response.data);
  }

  if (loginFilter.test(req.url) && typeof req.session.JSESSIONID !== 'undefined') {
    return res.redirect(Local.url);
  } else if (typeof req.session.JSESSIONID !== 'undefined') {
    return next();
  } else {
    return res.redirect(`${SSO.ssoOrigin + SSO.checkTicket}?url=${req.url}&login=${Local.url + '/login'}&appcode=${Local.appCode}`);
  }
});

// Listen the server
server.listen(port, host);
console.log('Server listening on ' + host + ':' + port); // eslint-disable-line no-console
